package test2;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-04-05
 * Time:17:43
 */
import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;

public class User extends JFrame implements ActionListener, Runnable{

    JTextField outMessage = new JTextField(12);//用于输入发送的数据
    JTextArea inMessage = new JTextArea(12,20);//用于展示接收和发送的消息
    JButton b = new JButton("发送数据");//发送按钮
    JButton clear = new JButton("清空");//清空按钮
    JButton exit = new JButton("退出");//退出按钮

    InetAddress dstAddr;//目标地址
    int dst;//目标端口号
    int src;//当前端口号
    String userName;//用户名

    //构造方法 - 创建聊天窗口
    public User(String other, String userName, InetAddress dstAddr, int dst, int src)
            throws UnknownHostException {
        super("与"+other+"的对话");//定义客户端窗口标题
        this.userName = userName;//初始化用户名
        this.dstAddr = dstAddr;//初始化目的地址
        this.dst = dst;//初始化目的端口号
        this.src = src;//初始化源端口号

        //为按钮添加监听
        b.addActionListener(this);
        clear.addActionListener(this);
        exit.addActionListener(this);

        setSize(600,500);//设置窗口大小
        setVisible(true);//设置窗口可见

        //将各图形化组件添加到窗口中
        JPanel p = new JPanel();
        p.add(outMessage);//发送的数据
        p.add(b);//添加发送按钮
        p.add(clear);//添加清空按钮
        p.add(exit);//添加退出按钮
        Container con = getContentPane();
        con.add(new JScrollPane(inMessage), BorderLayout.CENTER);//添加消息框
        con.add(p, BorderLayout.NORTH);//添加发送消息的面板

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        validate();

        Thread thread = new Thread(this);//为该用户创建线程
        thread.start(); //启动线程 - 负责接收数据
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource()==b){
            // 单击发送按钮
            byte b[] = (userName+":"+outMessage.getText()).trim().getBytes();//将用户要发送的内容加上用户姓名后整理
            //在用户自己的对话框中显示自己发送的内容
            inMessage.append(userName+"：");
            inMessage.append(outMessage.getText()+"\n");
            outMessage.setText("");//重置发送框中的信息
            //发送数据
            try {
                DatagramPacket dataPack = new DatagramPacket(b,b.length,dstAddr,dst);
                DatagramSocket send = new DatagramSocket();
                send.send(dataPack);
                send.close();
            } catch (SocketException socketException) {
                socketException.printStackTrace();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }else if (e.getSource()==clear){//单击清空按钮
            outMessage.setText("");//清空当前发送框中的信息
        }else if (e.getSource()==exit){//单击退出按钮
            this.dispatchEvent(new WindowEvent(this,WindowEvent.WINDOW_CLOSING) );//关闭窗口
        }
    }

    @Override
    public void run()
    {
        // 接收数据
        DatagramPacket pack = null;
        DatagramSocket mail = null;
        byte b[] = new byte[8192];
        try
        {
            pack = new DatagramPacket(b,b.length);
            mail = new DatagramSocket(src);
            while(true)
            {
                mail.receive(pack);
                String message = new String(pack.getData(),0,pack.getLength());
                //将接收到的数据添加到对话框中
                inMessage.append(message+"\n");
                inMessage.setCaretPosition(inMessage.getText().length());
            }
        }
        catch(Exception e){}
    }

    //修改swing全局字体 - 在main方法中生成其他GUI图形界面之前调用，可以将字体设置为我们传参的字体
    public static void InitGlobalFont(Font f){
        FontUIResource fontRes = new FontUIResource(f);
        for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof FontUIResource) {
                UIManager.put(key, fontRes);
            }
        }
    }

    public static void main(String[] args) {
        Font font = new Font("楷体",0,26);//创建字体对象
        User.InitGlobalFont(font);//将默认字体设置为全局字体
        try {
            //创建客户端
            User user1 = new User("用户2","用户1", InetAddress.getByName("localhost"),2345,2453);
            User user2 = new User("用户1","用户2", InetAddress.getByName("localhost"),2453,2345);
            //设置窗口位置和大小
            user1.setBounds(100,100,600,500);
            user2.setBounds(800,100,600,500);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

}
